package com.fulihui.wgj.schedule.job;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fulihui.common.enums.WxSystemConfigKeyEnum;
import com.fulihui.common.result.rpc.SimpleResult;
import com.fulihui.weixinsdk.WeixinSDK;
import com.fulihui.weixinsdk.request.ApiAuthorizerTokenRequest;
import com.fulihui.weixinsdk.result.ApiAuthorizerTokenResult;
import com.fulihui.wgj.facade.dto.WxPlatformDTO;
import com.fulihui.wgj.facade.result.system.WxSystemConfigResult;
import com.fulihui.wgj.facade.service.platform.WxPlatformService;
import com.fulihui.wgj.facade.service.system.WxSystemCongfigService;
import com.fulihui.wgj.schedule.annotation.MutexLock;
import com.fulihui.wgj.schedule.config.AppParamsConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: JY 刷新公众号Token
 * @date: 2018/6/22 14:24
 */
@Component
public class AuthorizerTokenJob {

    @Reference(version = "1.0.0")
    WxSystemCongfigService wxSystemCongfigService;

    @Reference(version = "1.0.0")
    WxPlatformService wxPlatformService;

    @Autowired
    WeixinSDK weixinSDK;

    @Autowired
    AppParamsConfig appParamsConfig;


    private static final Logger logger = LoggerFactory.getLogger(AuthorizerTokenJob.class);


    @MutexLock(node = "${job.node.authorizerTokenJob_entrance}")
    @Scheduled(cron = "${job.cron.authorizerTokenJob_entrance}")
    public void entrance() {

        //2.获取Ticket
        WxSystemConfigResult componentResult = wxSystemCongfigService.findConfigByCode(WxSystemConfigKeyEnum.component_access_token.getCode());

        //判断ComponentToken
        if (componentResult.getValue() == null || componentResult.getValue().isExire()) {
            logger.info("ComponentToken 失效 跳过刷新");
            return;
        }

        //获取公众号
        SimpleResult<List<WxPlatformDTO>> result = wxPlatformService.queryUsefulPlatform();
        //执行刷新公众号
        if (result.getData() != null && result.getData().size() > 0) {
            //遍历
            result.getData().forEach((item) -> {
                //刷新Token
                try {
                    refreshPlatformToken(item, componentResult.getValue().getDescript());
                } catch (Exception e) {
                    logger.info("公众号[{}]refreshPlatformToken异常{}", item.getAppId(), e.getMessage(), e);
                }
            });
        }
    }

    /**
     * 刷新Token
     *
     * @param platformDTO
     */
    private void refreshPlatformToken(WxPlatformDTO platformDTO, String ticket) {

        if (platformDTO == null || !platformDTO.isExire()) {
            return;
        }

        ApiAuthorizerTokenRequest tokenRequest = new ApiAuthorizerTokenRequest();
        tokenRequest.setComponent_appid(appParamsConfig.getAppId());
        tokenRequest.setComponent_access_token(ticket);
        tokenRequest.setAuthorizer_appid(platformDTO.getAppId());
        tokenRequest.setAuthorizer_refresh_token(platformDTO.getAuthorizerRefreshToken());
        //执行刷新
        ApiAuthorizerTokenResult tokenResult = weixinSDK.invokeService(tokenRequest);

        //更新数据库
        if (tokenResult != null && tokenResult.isSuccess()) {
            logger.info("Token 刷新成功 " + platformDTO.getAppId());
            wxPlatformService.updateToken(platformDTO.getAppId(), tokenResult.getAuthorizer_access_token(), tokenResult.getAuthorizer_refresh_token());
        }
    }
}
